package com.simtop.service.impl;

import com.baidu.aip.contentcensor.AipContentCensor;
import com.baidu.aip.contentcensor.EImgType;
import com.simtop.pojo.resource.Resources;
import com.simtop.service.CheckContent;
import com.simtop.service.ResourcesService;
import com.simtop.util.FileUploadAndDownload;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.auth0.jwt.internal.org.bouncycastle.crypto.tls.ConnectionEnd.client;
import static com.simtop.pojo.All.statusaus;


/**
 * @author lvyongwei
 */
@Service
public class CheckContentImpl implements CheckContent {

    @Autowired
    private AipContentCensor aipContentCensor;

    @Autowired
    private ResourcesService resourcesService;

    private Logger logger = LoggerFactory.getLogger(CheckContentImpl.class);


    /**
     * 审核图片
     *
     * @param path
     * @return
     */
    @Override
    @Async
    public void checkPhoto(String path, Long id) {
        try {
            JSONObject res = aipContentCensor.imageCensorUserDefined(path, EImgType.FILE, null);
            Resources resources = new Resources();
            resources.setId(id);
            resources.setCheckResult(res.toString());
            boolean b = resourcesService.updateResources(resources);
            if (!b) {
                logger.error("图片审核后插入数据库失败,时间是{},资源id为{}", new Date(), id);
            }
        } catch (Exception e) {
            logger.error("文件审核插入失败，请检查");
        }
    }

    /**
     * 文本审核
     *
     * @param text
     * @return
     */
    @Override
    public String checkText(String text) {
        try {
            // 参数为本地图片路径
            JSONObject response = aipContentCensor.textCensorUserDefined(text);
            return response.toString();
        } catch (Exception e) {
            logger.error("文本审核失败，请检查");
            return null;
        }
    }

    /**
     * 音频审核
     *
     * @param voice
     * @return
     */
    @Async
    @Override
    public void checkVoice(String voice, Long id) {
        try {
            //可选参数配置
            HashMap<String, String> options = new HashMap(2);
            options.put("rawText", "true");
            options.put("split", "true");
            // 参数为本地语音
//            String suffix = voice.substring(voice.lastIndexOf(".") + 1, voice.length());
            String voiceUrl = "http://www.simtop.online/editorCheck/profile/upload/" + statusaus;
            System.out.println(voiceUrl);
            //审核音频
            // JSONObject response = aipContentCensor.voiceCensorUserDefined(voice,EImgType.FILE,suffix,options);
            JSONObject response = aipContentCensor.asyncVoiceCensorSubmit(voiceUrl, "mp3", 16000, null);
            JSONObject datass = response.getJSONObject("data");
            String taskId = (String) datass.get("taskId");

            // sdk调用接口并输出结果
            String ABC = String.valueOf(aipContentCensor.asyncVoiceCensorPullByTaskId(taskId, null));
            Thread.sleep(5000);
            System.out.println(ABC);
            com.alibaba.fastjson.JSONObject vic = com.alibaba.fastjson.JSONObject.parseObject(ABC);

            String conclusion = null;
            conclusion = vic.getString("conclusion");
            if (conclusion != null) {
                //System.out.println(conclusion);
                String data = vic.getString("data");
                //System.out.println(conclusionTypeGroupInfos);
                Map<Object, Object> objectObjectMap = new HashMap<>();
                objectObjectMap.put("conclusion", conclusion);
                objectObjectMap.put("data", data);
                Object oS = com.alibaba.fastjson.JSONObject.toJSON(objectObjectMap);
                //添加审核结果
                Resources resources = new Resources();
                resources.setId(id);
                System.out.println("结果集"+oS.toString());
                resources.setCheckResult(oS.toString());
                resources.setTaskid(taskId);
                boolean b = resourcesService.updateResources(resources);
                if (!b) {
                    logger.error("音频审核后插入数据库失败,时间是{},资源id为{}", new Date(), id);
                }
            } else {
                Map<Object, Object> objectObjectMapas = new HashMap<>();
                objectObjectMapas.put("conclusion", "合规");
                Object oSs = com.alibaba.fastjson.JSONObject.toJSON(objectObjectMapas);
                //添加审核结果
                Resources resources = new Resources();
                resources.setId(id);
                System.out.println("结果集"+oSs.toString());
                resources.setCheckResult(oSs.toString());
                resources.setTaskid(taskId);
                boolean b = resourcesService.updateResources(resources);
                if (!b) {
                    logger.error("音频审核后插入数据库失败,时间是{},资源id为{}", new Date(), id);
                }
            }
        } catch (Exception e) {
            logger.error("音频审核插入失败，请检查");
        }

        //添加审核结果

    }


    /**
     * 视频审核
     *
     * @param video
     * @return
     */
    @Async
    @Override
    public void checkVideo(String video, Long id, HttpServletRequest request, Double lastSize) {

        String requestURI = request.getHeader("host");
        String contextPath = request.getContextPath();
        //视频url 地址
        //String videoUrl ="http://" + requestURI + contextPath  + video;
        //String videoUrl ="http:\\106.14.183.14:8903\\editorCheck"  + video;

        String videoUrl = "http://www.simtop.online/editorCheck/profile/upload/" + statusaus;
        System.out.println(videoUrl);
       // String videotest = "http://www.simtop.online/editorCheck/profile/upload/d63b4fc9-d916-4242-932d-2499787210fc.mp4";
        //视频名字
        String name = "videoName";
        //视频id;
        UUID uuid = UUID.randomUUID();
        String s = uuid.toString();
        int lastSizes = 100;
        if (lastSize < 50) {
            try {
                String res = String.valueOf(aipContentCensor.videoCensorUserDefined(name, videoUrl, s, null));
                com.alibaba.fastjson.JSONObject resS = com.alibaba.fastjson.JSONObject.parseObject(res);
                String conclusion = resS.getString("conclusion");
                //System.out.println(conclusion);
                String conclusionTypeGroupInfos = resS.getString("conclusionTypeGroupInfos");
                //System.out.println(conclusionTypeGroupInfos);
                Map<Object, Object> objectObjectMap = new HashMap<>();
                objectObjectMap.put("conclusion", conclusion);
                objectObjectMap.put("data", conclusionTypeGroupInfos);
                Object oS = com.alibaba.fastjson.JSONObject.toJSON(objectObjectMap);
                // System.out.println(oS);

                //添加审核结果
                Resources resources = new Resources();
                resources.setId(id);
                resources.setCheckResult(oS.toString());
                boolean b = resourcesService.updateResources(resources);
                if (!b) {
                    logger.error("视频审核后插入数据库失败,时间是{},资源id为{}", new Date(), id);
                }
            } catch (Exception e) {
                logger.error("视频审核插入失败，请检查");
            }

        } else {


            try {
                //设置链接超时时间
                // JSONObject res=aipContentCensor.videoCensorUserDefined(name, videotest, extId, null);
                JSONObject ress = aipContentCensor.longVideoCensorSubmit(videoUrl, s, null);
                JSONObject datass = ress.getJSONObject("data");
                String taskId = (String) datass.get("taskId");

                // sdk调用接口并输出结果
                String ABC = String.valueOf(aipContentCensor.longVideoCensorPull(taskId, null));
                Thread.sleep(5000);
                System.out.println(ABC);
                com.alibaba.fastjson.JSONObject resS = com.alibaba.fastjson.JSONObject.parseObject(ABC);
                String conclusion = resS.getString("conclusion");
                if (conclusion != null) {
                    //System.out.println(conclusion);
                    String conclusionTypeGroupInfos = resS.getString("conclusionTypeGroupInfos");
                    //System.out.println(conclusionTypeGroupInfos);
                    Map<Object, Object> objectObjectMap = new HashMap<>();
                    objectObjectMap.put("conclusion", conclusion);
                    objectObjectMap.put("data", conclusionTypeGroupInfos);
                    Object oS = com.alibaba.fastjson.JSONObject.toJSON(objectObjectMap);
                    //更新审核结果
                    Resources resources = new Resources();
                    resources.setId(id);
                    resources.setCheckResult(oS.toString());
                    resources.setTaskid(taskId);
                    boolean b = resourcesService.updateResources(resources);


                    if (!b) {
                        logger.error("视频审核后插入数据库失败,时间是{},资源id为{}", new Date(), id);
                    }
                } else {
                    Map<Object, Object> objectObjectMapas = new HashMap<>();
                    objectObjectMapas.put("conclusion", "合规");
                    Object oSs = com.alibaba.fastjson.JSONObject.toJSON(objectObjectMapas);
                    //添加审核结果
                    Resources resources = new Resources();
                    resources.setId(id);
                    resources.setCheckResult(oSs.toString());
                    resources.setTaskid(taskId);
                    boolean b = resourcesService.updateResources(resources);
                    if (!b) {
                        logger.error("视频审核后插入数据库失败,时间是{},资源id为{}", new Date(), id);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("视频审核插入失败，请检查");
            }

        }
    }
}
